package com.douya.security.utils;

import com.douya.security.property.DouYaSecurityProperties;
import com.douya.security.property.HeaderTokenProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * 说明: jwt工具类
 *
 * @author HCY
 * @date 2022-11-28 11:33
 */
@Component
public class JwtUtils {
    private final DouYaSecurityProperties mSecurityProperties;

    public JwtUtils(DouYaSecurityProperties mSecurityProperties) {
        this.mSecurityProperties = mSecurityProperties;
    }

    /**
     * 生成token的map,必须放id,subject,password,其他的可以选填如手机号码之类的.
     *
     * @param claims 生成token的map
     * @return token
     */
    @SuppressWarnings("deprecation")
    public String generateToken(Map<String, Object> claims) {
        HeaderTokenProperties headerToken = mSecurityProperties.getHeaderToken();
        return Jwts.builder()
                .setClaims(claims)
                .setId(claims.get("id").toString())
                .setSubject(claims.get("subject").toString())
                .setExpiration(DateUtils.addMinutes(new Date(), (int) headerToken.getExpireTime().toMinutes()))
                .signWith(SignatureAlgorithm.HS256, generalKey())
                .compact();
    }

    /**
     * 由字符串生成加密key
     */
    private String generalKey() {
        HeaderTokenProperties headerToken = mSecurityProperties.getHeaderToken();
        String stringKey = headerToken.getSecret();
        return Base64.encodeBase64String(stringKey.getBytes());

    }

    /**
     * 解密token
     *
     * @param token token
     */
    public Claims getClaimsFromToken(String token) {
        String key = generalKey();
        //签名秘钥，和生成的签名的秘钥一模一样
        return Jwts.parser()
                //得到DefaultJwtParser
                .setSigningKey(key)
                //设置签名的秘钥
                .parseClaimsJws(token).getBody();
    }

    /**
     * 从token中获取用户名
     *
     * @param token token
     * @return 用户名
     */
    public String getUsernameFromToken(String token){
        Claims claims = getClaimsFromToken(token);
        return claims.getId();
    }

}
